package com.education.platform.common.util;

import com.education.platform.common.exception.BusinessException;
import org.apache.commons.lang3.time.DateFormatUtils;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;

import java.util.*;

/**
 * 时间工具类
 */
public class DateUtils {


    public static final String DATE = "yyyy-MM-dd";
    public static final String DATE_HH_MM = "yyyy-MM-dd HH:mm";
    public static final String DATE_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";
    public static final String DATE_HH_MM_SS_Z1 = "yyyy-MM-dd'T'HH:mm:ss'Z'";
    public static final String DATE_HH_MM_SS_Z2 = "yyyy-MM-dd'T'HH:mm:ssZ";
    public static final String DATE_HH_MM_SS_Z3 = "yyyy-MM-dd'T'HH:mm:ssz";
    public static final String DATE_HH_MM_SS_Z4 = "yyyy-MM-dd'T'HH:mm:ss";

    public static final String DATE_HH_MM_SS_A = "MM/dd/yyyy HH:mm:ss a";
    public static final String DATE_HHMMSS = "yyyyMMddHHmmss";
    public static final String DATE_YEAR = "yyyy";
    public static final String DATE_MONTH = "yyyy-MM";
    public static final String DATE_DAY = "yyyy-MM-dd";
    public static final String DATE_YYYY_MM_DD = "yyyyMMdd";

    /**
     * 描述：获取指定日期的中文星期数
     *
     * @param date
     *            指定日期
     * @return 星期数，如：星期一
     */
    public static String getWeekStr(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int week = calendar.get(7);
        --week;
        String weekStr = "";
        switch (week) {
            case 0:
                weekStr = "星期日";
                break;
            case 1:
                weekStr = "星期一";
                break;
            case 2:
                weekStr = "星期二";
                break;
            case 3:
                weekStr = "星期三";
                break;
            case 4:
                weekStr = "星期四";
                break;
            case 5:
                weekStr = "星期五";
                break;
            case 6:
                weekStr = "星期六";
        }
        return weekStr;
    }
    /**
     * 描述：去除日期字串中原“-”和“:”
     *
     * @param dateTime 日期字串
     * @return
     */
    public static String formatString(String dateTime) {
        if ((dateTime != null) && (dateTime.length() >= 8)) {
            String formatDateTime = dateTime.replaceAll("-", "");
            formatDateTime = formatDateTime.replaceAll(":", "");
            String date = formatDateTime.substring(0, 8);
            return date;
        }

        return "";
    }
    /**
     * 描述：当前时间与指定时间的差
     *
     * @param str
     *            yyyy-MM-dd HH:mm:ss 格式的日期
     * @return 时间差，单位：秒
     */
    public static int getTimesper(String str) {
        if ((str == null) || ("".equals(str))) {
            return 0;
        }
        try {
            Date date1 = new Date(Long.parseLong(str));
            Date date = new Date();
            long nowtime = (date.getTime() - date1.getTime()) / 1000L;
            return (int) nowtime;
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("日期转换出错");
        }
        return 0;
    }
    /**
     * 字符串转化成日期
     *
     * @param dateString 字符串
     * @return 日期
     */
    public synchronized static Date parse(String dateString) {
        if (dateString == null) {
            return null;
        }
        try {
            return org.apache.commons.lang3.time.DateUtils.parseDate(dateString,
                    DATE_HH_MM_SS,
                    DATE_HH_MM,
                    DATE,
                    DATE_HH_MM_SS_Z1,
                    DATE_HH_MM_SS_Z2,
                    DATE_HH_MM_SS_Z3,
                    DATE_HH_MM_SS_Z4,
                    DATE_HH_MM_SS_A,
                    DATE_HHMMSS);
        } catch (ParseException e) {
            throw new RuntimeException("date parse exception:" + e.getMessage());
        }
    }


    /**
     * 日期类型转字符串
     *
     * @param date 日期
     * @return 字符串（格式为：yyyy-MM-dd）
     */
    public synchronized static String format(Date date) {
        return DateFormatUtils.format(date,DATE);

    }

    /**
     * 日期类型转字符串
     *
     * @param date    日期
     * @param pattern 格式
     * @return 字符串
     */
    public static String format(Date date, String pattern) {
        return DateFormatUtils.format(date,pattern);
    }


    /**
     * 得到两个时间的差额
     *
     * @param date      时间
     * @param otherDate 时间
     * @return 时间差额
     */
    public static long betDate(Date date, Date otherDate) {
        return date.getTime() - otherDate.getTime();
    }

    /**
     * 获取当前日期
     *
     * @return long（毫秒）
     */
    public static long getCurrentTime() {
        return Calendar.getInstance().getTimeInMillis();
    }

    /**
     * 获取当前日期
     *
     * @return Date
     */
    public static Date getCurrentDate() {
        return new Date();
    }

    /**
     * 获取当前日期
     *
     * @return Calendar
     */
    public static Calendar getCurrentCalendar() {
        return Calendar.getInstance();
    }

    public static String calendarToString(Calendar calendar, String template) {
        String stringCalendar = template;
        stringCalendar = stringCalendar.replace("{year}",
                String.valueOf(calendar.get(Calendar.YEAR)));
        stringCalendar = stringCalendar.replace("{month}",
                String.valueOf(calendar.get(Calendar.MONTH)));
        stringCalendar = stringCalendar.replace("{date}",
                String.valueOf(calendar.get(Calendar.DATE)));
        stringCalendar = stringCalendar.replace("{hour}",
                String.valueOf(calendar.get(Calendar.HOUR_OF_DAY)));
        stringCalendar = stringCalendar.replace("{minute}",
                String.valueOf(calendar.get(Calendar.MINUTE)));
        stringCalendar = stringCalendar.replace("{second}",
                String.valueOf(calendar.get(Calendar.SECOND)));
        stringCalendar = stringCalendar.replace("{millisecond}",
                String.valueOf(calendar.get(Calendar.MILLISECOND)));
        return stringCalendar;
    }

    /**
     * 比较时间差 1小时内的显示：**　分钟前，例如：25　分钟前 1小时前（１天内的）：今天　**时：**分，例如：　08：17
     * 1天前的（当前年）：*月*号　**时：**分，例如：05-09　23：58
     * 当前年之前的：年－月－日　**时：**分，例如：2009-09-26　16：33
     **/
    public static String timeCompare(Date nowArg, Date dateArg) {
        Calendar now = Calendar.getInstance();
        now.setTime(nowArg);
        Calendar date = Calendar.getInstance();
        date.setTime(dateArg);

        int nowY = now.get(Calendar.YEAR);
        int dateY = date.get(Calendar.YEAR);

        int nowM = now.get(Calendar.MONTH);
        int dateM = date.get(Calendar.MONTH);

        int nowD = now.get(Calendar.DAY_OF_MONTH);
        int dateD = date.get(Calendar.DAY_OF_MONTH);


        long l = now.getTimeInMillis() - date.getTimeInMillis();
        long m = nowM - dateM;
        long day = nowD - dateD;

        int dateHour = date.get(Calendar.HOUR_OF_DAY);
        int dateMinutes = date.get(Calendar.MINUTE);

        long hour = (l / (60 * 60 * 1000) - day * 24);
        long min = ((l / (60 * 1000)) - day * 24 * 60 - hour * 60);
        long y = nowY - dateY;
        String ret = "";
        if (y > 0) {
            //大于一年的
            ret += (dateY + 1900) + "-";
        }

        if (day > 0 || y > 0 || m > 0) {// 大于一天的
            if (dateM + 1 < 10) {
                ret += "0";
            }

            ret += (dateM + 1) + "-";
            if (dateD < 10) {
                ret += "0";
            }
            ret += dateD + " ";
        }
        if (hour > 0 || day > 0 || y > 0 || m > 0) {// 大于一小时
            if (dateHour < 10) {
                ret += "0";
            }
            ret += dateHour + ":";
            if (dateMinutes < 10) {
                ret += "0";
            }
            ret += dateMinutes;
        }
        if (y == 0 && (day * 24 + hour) == 0 && min != 0) {
            ret = min + " 分前";
        }
        if (y == 0 && (day * 24 + hour) == 0 && min == 0) {
            ret = "1  分前";
        }
        return ret;
    }

    public static long getFormatedTime(Date date) {
        if (date == null) {
            return 0;
        }
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        return new Long(dateFormat.format(date)).longValue();
    }

    public static Date parse(String str, String pattern) {
        DateFormat format = new SimpleDateFormat(pattern);
        Date date = null;
        try {
            date = format.parse(str);
        } catch (ParseException e) {
            throw new RuntimeException("date parse exception:" + e.getMessage());
        }
        return date;
    }


    public static int compare(Date start,Date end,String pattern){
       if(start == null || end == null){
           throw new BusinessException("日期不能为空");
       }
       if(pattern == null){
           pattern = DATE;
       }
        start = parse(format(start,pattern),pattern);
        end = parse(format(end,pattern),pattern);
       return end.compareTo(start);
    }


    public static int daydiff(Date startDate, Date endDate) {
        //判断是否跨年
        String startYear =format(startDate,DATE_YEAR) ;
        String endYear = format(endDate,DATE_YEAR);
        if (startYear.equals(endYear)) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(startDate);
            int startDay = calendar.get(Calendar.DAY_OF_YEAR);
            calendar.setTime(endDate);
            int endDay = calendar.get(Calendar.DAY_OF_YEAR);
            return endDay - startDay;
        } else {
            //  只格式化日期，消除不满24小时影响
            long startDateTime = parse(format(startDate,DATE),DATE).getTime();
            long endDateTime = parse(format(endDate,DATE),DATE).getTime();
            return (int) ((endDateTime - startDateTime) / (1000 * 3600 * 24));
        }

    }

}
